package cn.bdqn.page1;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 用户注册类
 */
public class Register {
	// 因为所有的方法都需要DOM树
	static Document document = null;
	static Element root = null;

	// 保存用户信息类
	public static void save(String path) {
		OutputFormat format = null;
		XMLWriter writer = null;
		try {
			format = OutputFormat.createPrettyPrint();
			writer = new XMLWriter(new FileWriter("UserMessage.xml"), format);
			writer.write(document);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	// 重写toString方法，需要把生成的电话号码转换成字符串
	public String toString(List<Integer> list) {
		String sum = list.get(0).toString();
		for (int i = 0; i < (list.size() - 1); i++) {
			String number = list.get(i + 1).toString();
			sum = sum.concat(number);
		}
		return sum;
	}

	// 选择卡号（从随机生成的9个以“139”开头的卡号中选择一个，输入序号即可）
	public void getPhoneNum() throws Exception {
		Scanner input = new Scanner(System.in);
		// 进行dom4j解析
		SAXReader reader = new SAXReader();
		List<String> list = new ArrayList<String>();
		// 创建document对象
		document = reader.read("UserMessage.xml");
		// 实现根节点users的读取，根节点有且只有一个
		root = (Element) document.getRootElement();
		// 循环遍历找到users节点
		Iterator Users = root.elementIterator();
		while (Users.hasNext()) {
			Element user = (Element) Users.next();
			// 读取到已经存储到xml文件中的电话号码和密码
			List<String> phoneName = new ArrayList<String>();
			phoneName.add(user.attributeValue("id"));
			List<String> pwd = new ArrayList<String>();
			// 进行注册前的选择
			System.out.println("********可选择的卡号：********");
			String phone1 = "139";
			// 生成的随机的号码
			String phone = null;
			// 用来存储随机数的集合
			List<Integer> num = new ArrayList<Integer>();
			// 用map来存储序号和电话号码，然后写入xml文件
			Map<Integer, String> map = new HashMap<Integer, String>();
			// 循环产生电话号码，并存储到map中
			for (int i = 1; i <= 9; i++) {
				for (int j = 0; j < 8; j++) {
					Random rand = new Random();
					int num1 = rand.nextInt(10);
					num.add(num1);
				}
				Register re = new Register();
				String phone2 = re.toString(num);
				phone = (String) phone1.concat(phone2);
				map.put(i, phone);
				// 遍历map 首先获取所有的key集合
				Set<Integer> set = map.keySet();
				System.out.println("生成的第" + i + "个号码：" + phone);
				num.clear();
				map.clear();
			}
			System.out.print("请选择卡号（输入1~9之间的序号）：");
			int choose = input.nextInt();
			// 遍历map 首先获取所有的key集合
			Set<Integer> set = map.keySet();
			boolean isPhone = false;
			// 选择对了，存储下号码
			for (int i = 0; i < set.size(); i++) {
				Iterator userId = root.elementIterator();
				while (userId.hasNext()) {
					Element element = (Element) userId.next();
					// 获取属性值，判断是不是
					if (element.attribute("id").equals(map.get(i + 1))) {
						isPhone = true;
						System.out.println("有重复电话号码！");
					}
				}
			}
			// 新开一个节点，把电话号码存储进去
			Element element = root.addElement("user");
			if (isPhone == true) {
				System.out.println("选择错误，没有正确选择到电话号码！");
			} else {

				// 节点设置属性
				element.addAttribute("id", phone);
			}
			save("UserMessage.xml");
			System.out.print("1、话唠套餐\t2、网虫套餐\t3、超人套餐\t请选择套餐（输入序号）：");
			int taoCan = input.nextInt();
			switch (taoCan) {
			case 1:
				// 节点设置属性
				element.addAttribute("longCall", "500分钟");
				element.addAttribute("internetTraffic", "0G");
				element.addAttribute("shortMessage", "30条");
				element.addAttribute("money", "58元/月");
				break;
			case 2:
				// 节点设置属性
				element.addAttribute("longCall", "0分钟");
				element.addAttribute("internetTraffic", "3G");
				element.addAttribute("shortMessage", "0条");
				element.addAttribute("money", "68元/月");
				break;
			case 3:
				// 节点设置属性
				element.addAttribute("longCall", "200分钟");
				element.addAttribute("internetTraffic", "1G");
				element.addAttribute("shortMessage", "50条");
				element.addAttribute("money", "78元/月");
				break;
			default:
				System.out.println("选择错误，默认选择超人套餐");
				// 节点设置属性
				element.addAttribute("longCall", "200分钟");
				element.addAttribute("internetTraffic", "1G");
				element.addAttribute("shortMessage", "50条");
				element.addAttribute("money", "78元/月");
				break;
			}
			save("UserMessage.xml");
			System.out.print("请输入姓名：");
			String name = input.next();
			element.addAttribute("name", name);
			System.out.print("请输入密码：");
			String password = input.next();
			element.addAttribute("pwd", password);
			System.out.print("请输入预存话费金额：");
			double money = input.nextDouble();
			Double money1 = new Double(money);

			if (Double.parseDouble(((String) element.attributeValue("money"))
					.substring(0, 2)) > money) {
				System.out.print("您预存的话费金额不足以支付本月固定套餐资费，请重新充值：");
				money = input.nextDouble();
				money1 = new Double(money);
				element.attribute("recharge").setValue(money1.toString());
				if (Double.parseDouble(((String) element
						.attributeValue("money")).substring(0, 2)) <= money) {
					System.out.println("充值成功！");
				}
			} else {
				System.out.println("充值成功！");
			}
			String balance = ((Double) (money - Double
					.parseDouble(((String) element.attributeValue("money"))
							.substring(0, 2)))).toString();
			element.addAttribute("balance", balance);
			System.out.println("注册成功！卡号：" + element.attributeValue("id")
					+ "\t用户名：" + element.attributeValue("name") + "\t当前余额："
					+ element.attributeValue("balance") + "。");
			save("UserMessage.xml");
			switch (taoCan) {
			case 1:
				System.out.println("话唠套餐：通话时长为："
						+ element.attributeValue("longCall") + ",上网流量为："
						+ element.attributeValue("internetTraffic") + ",短信条数为："
						+ element.attributeValue("shortMessage") + "。");
				break;
			case 2:
				System.out.println("网虫套餐：通话时长为："
						+ element.attributeValue("longCall") + ",上网流量为："
						+ element.attributeValue("internetTraffic") + ",短信条数为："
						+ element.attributeValue("shortMessage") + "。");
				break;
			case 3:
				System.out.println("超人套餐：通话时长为："
						+ element.attributeValue("longCall") + ",上网流量为："
						+ element.attributeValue("internetTraffic") + ",短信条数为："
						+ element.attributeValue("shortMessage") + "。");
				break;

			}
			save("UserMessage.xml");

			return;
		}
		// 还有一个保存用户信息没有写，那个还是要写的
		save("UserMessage.xml");

	}

}
